<template>
  <div class="app-container">
    <div role="alert" v-show='bools' class="el-message el-message--warning" style="top: 20px; z-index: 2002;"><i class="el-message__icon el-icon-warning"></i><p class="el-message__content">必须要有相同的Coach/Helper/Athlete 才可以批量修改！</p><!----></div>
    <!--    ime-mode: disabled-->
    <div id="courseAddEdit" :class="info.modify ? 'container-fluid add-page': 'container-fluid add-page disabled-input'">
      <el-form ref="course" :model="info.course" :rules="rules.course">
        <!-- add 标题显示 end-->
        <el-row :gutter="20" class="solid-row course_mat_box">
          <el-col :sm="20">
            <el-row :gutter="20">
              <el-col :sm="3" class="ul-input"><el-form-item>Course information:</el-form-item></el-col>
              <el-col v-for="(items,i) in sortName" :key="i" :sm="7" class="ul-input">
                <el-form-item :prop="items.key">
                  <el-select  v-if="i== 0"  v-model="info.course[items.key]" @change="(val,e)=>changeSport(val,e,i)" :placeholder="items.label">
                    <template v-for="item in sortName[0].list">
                      <el-option
                        v-if="item.typeCode===items.typeCode"
                        :key="item.id"
                        :label="item.typeName"
                        :value="item.id"
                      />
                    </template>
                  </el-select>
                  <el-input v-else @change="(val,e)=>changeSport(val,e,i)" v-model="info.course[items.key]" :placeholder="items.label"/>

                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :sm="4" class="ul-input">
            <el-button v-if="true" type="success" :loading="loadcourse" @click="confirmCourse('course')"> Confirm</el-button>
            <el-button v-else-if="true" type="success"> Edit</el-button>
            <el-button v-else type="success"> confirm</el-button>
          </el-col>
        </el-row>

      </el-form>
<!--      {{isCourseFormation}} -->
      <el-form ref="lesson" :model="info.lesson" :rules="rules.lesson">
        <!--  -->
        <el-row :gutter="20" class="solid-row call_method_box">
          <el-col :sm="4" :md="3" :lg="3" :xl="2" class="ul-input">
           Roll call method:
          </el-col>
          <el-col :sm="10" :md="11" :lg="9" :xl="6">
            <el-form-item prop="rollCallMethod">

              <el-checkbox-group @change="addEdit('course',true)" v-model="rollCallMethod" class="ul-input">
                <el-checkbox :disabled="!course"  key="ROLL_MANUAL_INPUT" :label="&quot;ROLL_MANUAL_INPUT&quot;">Coach Manual Input</el-checkbox>
                <el-checkbox :disabled="!course" key="ROLL_COACH_SCAN" :label="&quot;ROLL_COACH_SCAN&quot;">Coach Scan</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :sm="8" :md="10" :lg="9" :xl="7">
            <el-form-item label="Rate Card:" prop="rateCard" class="ul-input">
              <el-select @change="addEdit('course',true)" :disabled="!course" v-model="info.lesson.rateCard" placeholder="Rate Card:">
                <template v-for="item in info.rateCard">
                  <el-option v-if="item" :key="item.id" :label="item.name" :value="item.id" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="solid-row">
          <el-col :lg="5" class="ul-input">
            <el-form-item prod='size'>
              <el-input v-show='false' :value="20" />
              <span class="demonstration ">Lesson Information：</span>
            </el-form-item>
             </el-col>
            <el-col :lg="9" class="ul-input">
            <el-form-item prop="start">
              <el-date-picker
                v-model="dateRang"
                :disabled="!course"

                type="daterange"
                range-separator="-"
                value-format="yyyy-MM-dd"
                start-placeholder="Start Date"
                end-placeholder="End Date"
              /></el-form-item>
          </el-col>
          <el-col :lg="9" :offset="1" class="ul-input">
            <!-- <el-time-select
            :disabled="!course"
                placeholder="Start Time"
                v-model="info.lesson.startTime"
                :picker-options="{
                  start: '06:30',
                  step: '00:05',
                  end: '23:30'
                }">
              </el-time-select>
              <span class="pad">-</span>
              <el-time-select
              :disabled="!course"
                placeholder="End Time"
                v-model="info.lesson.endTime"
                :picker-options="{
                  start: '06:30',
                  step: '00:05',
                  end: '23:30',
                  minTime: info.lesson.startTime
                }">
              </el-time-select> -->

          <div class='timerBox flex-box coll'>
              <el-form-item  prop="startTime" style="margin: 0;">
                <VueTimepicker
                 ref='startRef'
                 v-model="info.lesson.startTime" format="HH:mm" :minute-interval="5" lazy></VueTimepicker>
                </el-form-item>
                 <span class="pad" style="padding:6px;">-</span>
                <el-form-item  prop="endTime" style="margin: 0;">
                 <VueTimepicker
                     ref='endRef'
                   @change='_endMinuteRang'
                   v-model="info.lesson.endTime" format="HH:mm" :minute-interval="5" lazy></VueTimepicker>
                  </el-form-item>
          </div>
        <!--  <el-form-item  prop="startTime">

  <div class="flex-box">
     <VueTimepicker
      :minute-range="[0,5,[5,info.lesson.endTime?info.lesson.endTime.split(':')[1]:60],60]"
      :hour-range="[0,1,[1,info.lesson.endTime?info.lesson.endTime.split(':')[0]:24],24]"
      v-model="info.lesson.startTime" format="HH:mm" :minute-interval="5" lazy></VueTimepicker>
     <span class="pad">-</span>
      <VueTimepicker
       :minute-range="endMinuteRang"
       @change='_endMinuteRang'
       :hour-range="[Number(info.lesson.startTime.split(':')[0]),Number(info.lesson.startTime.split(':')[0]),[Number(info.lesson.startTime.split(':')[0]),24],24]"
       v-model="info.lesson.endTime" format="HH:mm" :minute-interval="5" lazy></VueTimepicker>
   </div> -->
            <!-- <el-time-picker
              :disabled="!course"
                v-model="timeRang"
                is-range
                ref='timerRefs'
                format="HH:mm"
                value-format="HH:mm"
                :step="'05'"
                :picker-options="pickerOptions"

                range-separator="-"
                start-placeholder="Start Time"
                end-placeholder="End Time"

              /> -->
            <!--</el-form-item>-->
          </el-col>
          <el-col :sm="20">
            <el-row :gutter="20">
              <el-col :sm="7">
                <el-form-item prop="intervalType">
                  <el-select v-model="info.lesson.intervalType" placeholder="Interval">
                    <template v-for="item in ['WEEKLY','BIWEEKLY','MONTHLY','NONE']">
                      <el-option :key="item" :label="item" :value="item" />
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="7">
                <el-form-item prop="location">
                  <el-select :disabled="!course" v-model="info.lesson.location" :placeholder="'Venue'">
                    <template v-for="item in sortName[0].list">
                      <el-option v-if="item.typeCode=='VENUE'" :key="item.id" :label="item.typeName" :value="item.id" />
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="10">
                <el-form-item prop="week">
                  <el-checkbox-group :disabled="!course"  v-model="weekVal">
                    <el-row style="width:100%">
                      <el-col
                        v-for="(list,l) in WeekList"
                        :key="l"
                        :span="3.1"
                        style="margin-left:5px;"
                      >
                        <el-checkbox-button :key="list.value" class="el-checkbox-button--text" :label="list.value">{{ list.label }}</el-checkbox-button>
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-form-item v-show="false" prop="actionInstruct">
            <input :disabled="!course" v-model="this.actionToken" type="text">
          </el-form-item>
          <el-col :sm="4" class="ul-input">
            <el-button type="success" :disabled="!course"  :loading="loadlesson" @click="confirmCourse('lesson')"> Add</el-button>
          </el-col>
        </el-row>

      </el-form>
      <el-form ref="LessonList">
        <div v-show="lesson" style="margin:10px 0;"> Lesson List</div>
        <el-table
          v-show="lesson || lessonList.length"
          ref="table"

          v-loading="listLoading"
          :data="lessonList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row

          stripe
          @select="selectSingle"
          @select-all="selectAll"
          @selection-change="handleSelectionChange"
        >
          <!-- @sort-change="sort_change" -->
          <el-table-column
            type="selection"
            fixed="left"
            width="40"
            :selectable="signMd5selectable"
          />
          <el-table-column fixed="left" width="60" label="ID" prop="id" >
            <template slot-scope="scope">
              <el-button type="text" class="router-link-exact-active router-link-active" @click='toEdit([scope.row.id])'

              >
              {{ (scope.$index +1)+((listQuery.page-1)*listQuery.size) }}

<!--            {{ scope.$index>10?scope.$index + 1:'0'+(scope.$index + 1) }}   -->
              </el-button >
            </template>
          </el-table-column>
          <el-table-column label="Date" min-width="175" prop="upperDate" >
            <template slot-scope="scope">

              <!-- <el-input v-if="scope.row.edit" v-model="scope.row._upperDate" class="edit-input" size="small" /> -->
              <el-date-picker
              style="width: 100%;"
              v-if="scope.row.edit"
              format="yyyy - MM - dd"
              value-format="yyyy-MM-dd"
                  placeholder="Date"
                  v-model="scope.row._upperDate"
                  >
                </el-date-picker>
              <template v-else>
                {{ scope.row.upperDate | dateFormat }}
              </template>
            </template>
          </el-table-column>

          <el-table-column label="Day of the week" prop="upperWeek" >
            <template slot-scope="scope">
              {{ scope.row.upperWeek }}
            </template>
          </el-table-column>
          <el-table-column :label="'Start Time'" class-name="starlOv" width="120" align="center" prop="startTime" >
            <template slot-scope="scope">
              {{clearTimeFn('_startRef',scope)}}
              <VueTimepicker
                :ref='"_startRef"+scope.$index'
               v-if="scope.row.edit"
               v-model="scope.row._startTime" format="HH:mm" :minute-interval="5" lazy></VueTimepicker>
          <!--    {{scope.row._endTime}} -->
              <!-- <el-time-picker
              style="width: 100%;"
               v-if="scope.row.edit"
              :disabled="!course"
                v-model="scope.row._startTime"
                :is-range='false'
                format="HH:mm"
        :picker-options="{
            selectableRange:'04:30:00 - '+('23:59:00')
                    }"
                value-format="HH:mm"
                :step="'05:50'"
                range-separator="-"
                start-placeholder="Start Time"
                end-placeholder="End Time"
              /> -->
              <!-- <el-time-select
              style="width: 100%;"
              v-if="scope.row.edit"

                  placeholder="Start Time"
                  v-model="scope.row._startTime"
                  :picker-options="{
                    start: '06:30',
                    step: '00:05',
                    end: '23:30'
                  }">
                </el-time-select> -->
             <!-- <el-input v-model="scope.row._startTime"  class="edit-input" size="small" /> -->

              <template v-else>
                {{ scope.row.startTime }}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            :label="'End Time'"
            type="index"
            :index="indexMethod"
            width="120"
            align="center"
            prop="endTime"
            class-name="starlOv"
          >
            <template slot-scope="scope">

              <!-- <el-input
               v-if="scope.row.edit" v-model="scope.row._endTime" class="edit-input" size="small" /> -->
              <!-- <el-time-picker
               style="width: 100%;"
                v-if="scope.row.edit"
               :disabled="!course"
                 v-model="scope.row._endTime"
                 :is-range='false'
                 format="HH:mm"
                 value-format="HH:mm"
                 :step="'05:50'"
                 :picker-options="{
                       selectableRange:(scope.row._startTime?scope.row._startTime+':00':'04:31:00')+' - 23:59:00'
                     }"
                 range-separator="-"
                 start-placeholder="Start Time"
                 end-placeholder="End Time"
               /> -->
                 <!-- <el-time-select
                 style="width: 100%;"
                 v-if="scope.row.edit"

                     placeholder="Start Time"
                     v-model="scope.row._endTime"
                     :picker-options="{
                       start: '06:30',
                       step: '00:05',
                       end: '23:30',
                        minTime: scope.row._endTime
                     }">
                   </el-time-select> -->
                   <!-- {{clearTimeFn('_endRef',scope)}} -->

                   <VueTimepicker

                    :ref='"_endRef"+scope.$index'
                    v-if="scope.row.edit"
                    v-model="scope.row._endTime" format="HH:mm" :minute-interval="5" lazy></VueTimepicker>
              <template v-else>
                {{ scope.row.endTime }}
              </template>
            </template>
          </el-table-column>

          <el-table-column label="Location" min-width="100" prop="locationName" >
            <template slot-scope="scope">

          <!--   <el-input v-if="scope.row.edit" v-model="scope.row._locationName" class="edit-input" size="small" /> -->
             <el-select v-if="scope.row.edit"  v-model="scope.row._location" :placeholder="'Venue'">
               <template v-for="item in sortName[0].list">
                 <el-option v-if="item.typeCode=='VENUE'" :key="item.id" :label="item.typeName" :value="item.id" />
               </template>
             </el-select>
			  <template v-else>
                {{ scope.row.locationName || '-' }}
              </template>
            </template>
          </el-table-column>

          <el-table-column label="Coach/Helper" min-width="100" prop="coachNum" >
            <template slot-scope="scope">
              {{ scope.row.coachNum || '0' }}
            </template>
          </el-table-column>

          <el-table-column label="Athlete" min-width="100" prop="athleteNum" >
            <template slot-scope="scope">
              {{ scope.row.athleteNum || '0' }}
            </template>
          </el-table-column>

          <el-table-column label="Status" prop="pic" >
            <template slot-scope="scope">
              {{ scope.row.status }}
            </template>
          </el-table-column>
          <el-table-column :label="'Last Modified time'" width="180" align="center" prop="cts" >
            <template slot-scope="scope">
              {{ scope.row.cts | dateFormat('','','{d}-{m}-{y} {h}:{i}:{s}')}}
            </template>
          </el-table-column>

          <el-table-column  fixed="right" prop="id" label="" width="90">
            <template slot-scope="scope">

               <EditDel :scope="scope" @confirmEdit='confirmEdit' @close='close' @del='del' />
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="sizes, prev, pager, next"
          :page-size="listQuery.size"
          :current-page="listQuery.page"
          :total="listQuery.total"
          class="pagination-container"
          :page-sizes="[25, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />

        <!-- <template v-if="ENV === 'development'">
          <div v-for="(item, i) in info">
            <p><b>{{i}}</b>: {{JSON.stringify(item)}}</p>
          </div>
        </template> -->

        <el-form-item style="margin: 0;text-align: center;">
          <el-button v-if="target != 'blank'" type="success" size="medium" @click="onBack">Back</el-button>

          <el-button v-show="lesson||lessonList.length" type="success" size="medium" @click="onBulkSubmit">Bulk Edit</el-button>
          <el-button v-show="(course&&lesson)||$route.query.actionInstruct" type="success" size="medium" @click="onSave">Save</el-button>
           <el-button v-show="(course&&lesson)||$route.query.actionInstruct" type="success" size="medium" @click="onCopy">Copy</el-button>
            <el-button v-show="(course&&lesson)||$route.query.actionInstruct" type="success" size="medium" @click="onDetele">Delete</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
    // import draw from './profileDetails'
    import { getToken } from '@/utils/auth'
    // Main JS (in UMD format)


    // CSS

    import store from '@/store'
    // eslint-disable-next-line no-unused-vars
    import { addPersonnel, modifyPersonnel, getBelongingTypes, getUserList, queryAthletesList, queryUserList } from '@/api/setting'
    import { addEdit,
     getTypeCodeList,
     getCourseActionInstruct,
     updateInfo,
     delInfo,
     asyncGet,
     copyInfo
      } from '@/api/trainSchedule'

    // const start = new Date()
    // start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    export default {
        components: {
            // draw
        },
        data() {
            return {
                APP_BASE_API: process.env.VUE_APP_BASE_API,
                ENV: process.env.VUE_APP_ENV,
                WeekList: this.$store.state.app.WeekList,
                multipleSelections: [],
                signMd5selectable: (row, index) => {

                      // console.log("bool",this.bools)
                      return true
                },
                updateInfo,
                copyInfo,
                imgs: [],
                bool:false,
                activeName: 'Course',
                pageType: 'SportMedical',
                myHeaders: { Authorization: getToken() },
                actionToken: '',
                rollCallMethod: [],
                timeRang: '',
                dateRang: [new Date,],
                course: false,
                lesson: false,
                 sortName: [{
                      belonging: 'MISCELLANEOUS',
                      typeCode: 'SPORTS_TYPE',
                      typeName: 'Sport',
                       key: 'sport',
                      label: 'Sport',
                      value: '',
                       list: []
                     },
                    {
                       typeCode: 'COURSE_TYPE',
                       typeName: 'Course Name',
                       belonging: 'TRAINING',
                       label: 'Course Name',
                       key: 'course',
                       value: ''
                     },
                     {
                       typeCode: 'COURSE_DETALL',
                       typeName: 'Course Detalls',
                       belonging: 'TRAINING',
                       label: 'Course Detall',
                       key: 'courseDetails',
                       value: ''
                     }],
                     loadlesson:false,
                     loadcourse:false,
                info: {
                  rateCard: [],
                  course: {
                     sport: '', // 运动id
                     course: '', // 课程id
                     courseDetails: '', // 课程信息id
                     actionInstruct: ''
                  },

                  lesson: {
                    startTime: '', // 开始时间 格式HH:mm
                    endTime: '', // 结束时间 格式 HH:mm
                    location: '', // （也就是地址id）
                    rateCard: '',
                    rollCallMethod: '',
                    status: 'ACTIVE',
                    start: '',
                    end: '', // 结束日期 格式yyyy-MM-dd
                    week: '',
                    intervalType: '',
                    actionInstruct: ''
                  }
                },
                checkList: ['Coach Manual InputCoach', 'ScanRate'],
                weekVal: [],
                rules: {

                  course: {
                    sport: [
                  { required: true, trigger: 'change', message: 'please put in sport' }
                  // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                  // 运动id
                  course: [
                  { required: true, message: 'please put in course', trigger: 'change' }
                  // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                  // 课程id
                  courseDetails: [
                  { required: true, message: 'please put in courseDetails', trigger: 'change' }
                  // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                  // 课程信息id
                  actionInstruct: [
                  { required: true, message: 'please put in actionInstruct' }
                ]
                },

                lesson:
                 {
                   startTime: [
                  { required: true, message: 'Please select start time', trigger: 'change' }
                  ],

                  endTime: [
                  { required: true, message: 'Please select end time' }
                  ],

                  location: [
                  { required: true, message: 'Please put in location' }
                ],

                  rateCard: [
                  { required: false, message: 'Please put in Card Rate' }

                ],
                rollCallMethod: [
                  { required: true, message: 'Please put in rollCallMethod' }

                ],
                 status: [
                  { required: true, message: 'Please put in status' }

                ],
                 start: [
                  { required: true, message: 'Please select start Date' }
                  ],
                  end: [
                    { required: true, message: 'Please select end Date' }
                  ],
                  week: [
                  { required: true, message: 'Please put in week' }
                   ],
                  intervalType: [
                  { required: true, message: 'Please put in intervalType' }

                 ]
                }
                },
                id: '',
                lessonList: [],
                inputReadonly: false,
                sportMedicineList: {
                  },
                bools:false,
                list: [],
                indSportName:'',
                listQuery: {
                    page: 1,
                    size:25,
                    actionInstruct:'',
                    courseId:''
                   // limit: 25,
                   // total: 0,
                    //sorting: '',
                    //column: '',
                    //startDate: '',
                    //endDate: ''
                },
                sportScienceList: {
                    list: [],
                    listQuery: {
                        page: 1,
                        limit: 25
                    }
                },
                spinner:{
                  minutesList:[]
                },
                listLoading: false,
                link: '/trainSchedule/add',
                summaryList: [],
                listIndexs: [],
                minWindths: [],
                userType: store.getters.userType

            }
        },
        computed: {
          isCourseFormation(){
           var courseRef = this.$refs.course,that=this
           if(courseRef){
             courseRef.validate((res)=>{
               that.course =  res
             })
           }

           console.log('course', that.course)
           return that.course ;
          },
          },
        watch: {
          bools(){
            var that=this
             setTimeout(()=>{
               that.bools=false
             },800)

          },
          ['info.lesson.startTime'](e){
          if(this.info.lesson.endTime){
            if(this.timeLeng(e)>=this.timeLeng(this.info.lesson.endTime)){
              this.$refs.startRef.clearTime()
            }
          }
          },
          ['info.course.sport'](val){
            let that = this

                 this.sortName[0].list.map((lis)=>{
                   if(lis.id === val){
                      that.indSportName = lis.typeName
                      that.resetRouteTitle()
                      return
                   }
                 })
          },
          ['info.lesson.endTime'](e){
              if(this.info.lesson.endTime){
                if(this.timeLeng(e)<=this.timeLeng(this.info.lesson.startTime)){
               this.$refs.endRef.clearTime()
                }
          }
              console.log('endTime',this.info.lesson.endTime)
             },
           $route: {
                handler: function(route) {
                  // debugger
                    this.target = route.query && route.query.target
                    this.id = route.query.id || route.query.id === 0
                    this.listQuery.page = Number(route.query.pageNum) || this.listQuery.page
                    this.listQuery.size = Number(route.query.size) || this.listQuery.size;
                    this.listQuery.courseId =  Number(route.query.id)||''
                    this.listQuery.actionInstruct = route.query.actionInstruct||''
                },
                immediate: true
            },
            actionToken(val) {
                this.info.lesson.actionInstruct = val
            },
            weekVal(val) {
               this.info.lesson.week = val.join()
            },
            rollCallMethod(val) {
             // val = 'ROLL_MANUAL_INPUT'
            let isObjs = typeof(val) ==='object'
           if(isObjs){
            this.info.lesson.rollCallMethod =val.length >1? 'ROOL_ALL' : val[0]
             this.info.course.rollCallMethod =val.length >1? 'ROOL_ALL' : val[0]
           }else{
             this.info.lesson.rollCallMethod = val
             this.info.lesson.rollCallMethod =val
              this.rollCallMethod = val==='ROOL_ALL'?['ROLL_MANUAL_INPUT','ROLL_COACH_SCAN']:val?[val]:[]
           }

            },
            dateRang(e) {
              console.log('e', e)
              this.info.lesson.start = e[0]
              this.info.lesson.end = e[1]

            },
            timeRang(t) {
              //console.log('t', t)
              let timerRefs =  this.$refs.timerRefs

              this.info.lesson.startTime = t[0]
              this.info.lesson.endTime = t[1]
                this._endMinuteRang()
              //console.log('timerRefs',t[1],t[1])
            }
            // lessonList(val) {
            //   this.listLoading=val.length
            // }
        },
        created() {

        const query = this.$route.query
            if (query.tab) {
                this.activeName = query.tab || 'Course'
            }
            this.getCourseActionInstruct()
            this.fetchData()
        },
        mounted() {
          let timerRefs =  this.$refs.timerRefs
        //   var adjustSpinners = timerRefs.panel.methods.adjustSpinners
           console.log('params', timerRefs)
          var that = this
           // adjustSpinners=function (e){
           //  console.log('adjustSpinners', e,this)
           //  var  listf = [0,5,10,15,20,25,30,35,40,45,50,55,60]
           // }
           // adjustSpinners.spinner.minutesList = [0,5,10,15,20,25,30,35,40,45,50,55,60]
        },
        methods: {
          clearTimeFn(endRef,scope){
   //          let row = scope.row
   //           let isSt = endRef.indexOf('start')<=-1
   //          let endRefInfo =row[!isSt?'_startTime':'_endTime']
   //          let t2 = row[isSt?'_startTime':'_endTime']
   // //console.log('所说的方法',row, this.$refs,this.$refs[endRef+scope.$index])
   //        if(t2){
   //            if(isSt){
   //              if(this.timeLeng(t2)<=this.timeLeng(endRefInfo)){
   //                 console.log('end',this.timeLeng(t2),this.timeLeng(endRefInfo),endRef)
   //                  // this.$message({type:'warning',message:'End time cannot be less than end time!'})
   //                 this.$set(row,'require','End time cannot be less than start time!')
   //               return this.$refs[endRef+scope.$index].clearTime()

   //              }

   //            }else{
   //              if(this.timeLeng(t2)>=this.timeLeng(endRefInfo)){
   //                 console.log('str',t2,endRefInfo,this.timeLeng(t2)<=this.timeLeng(endRefInfo))

   //                 this.$set(row,'require','Start time cannot be greater than end time!')
   //               return this.$refs[endRef+scope.$index].clearTime()

   //              }

   //            }


   //          }
          },
          timeLeng(e){
           return  new Date(this.getToDay()+' '+e).getTime()
          },
          changeSport(val,e,i){

            if(!i&&val.typeName){
              this.info.course.sport = val.typeName
            }else {
              this.info.course[i===1?'course':'courseDetail'] =val
            }
            this.resetRouteTitle()
          },
          resetRouteTitle(){

            let {course,courseDetails} = this.info.course

            this.$parent.$parent.$children[1].$children[1].levelList[2].meta.title = this.indSportName+' '+course+' '+courseDetails
          },
          _endMinuteRang(e){
             let info =this.info
             let endHour = Number(info.lesson.endTime.split(':')[0]),
                 endMinu = Number(info.lesson.endTime.split(':')[1]),
                 starHour = Number(info.lesson.startTime.split(':')[0]);
             let _star= endHour < starHour
            console.log('es',starHour)
            return  !_star?endHour === starHour?[endMinu,[endMinu,50],[endMinu,50],55]:[]:[]
           },
          arrayUnique2(ary, name) {
         // 定义一个空对象来做存储判断
        const hasMap = {}
        ary.forEach(fileInfo => {
        // 取出每一项中的nodeId和fileName=>ES6的解构赋值
        const { name, fileName } = fileInfo
        // 如果对应的id在对象中不存在的话，我们将name作为key将fileName作为value
        if (!hasMap[name]) {
        hasMap[name] = fileName
        }
         // 如果存在的话的在原有的name上面拼接上这个fileName
        else {
        hasMap[name] += fileName
        }
        })
           /* object.values(obj),返回一个数组，其元素是在对象找到可枚举属性值。属性的顺序于通过手动循环对象的属性值所给出的顺序相同，
          obj被返回可枚举属性值对象，
          返回值一个包含对象自身的所有可枚举属性值得数组 */
          console.log('Object.values(hasMap)',Object.values(hasMap))
        return Object.values(hasMap)
        },
             getCourseActionInstruct() {
              var courseId = this.$route.query.id

              if (this.$refs.table) this.$refs.table.clearSort()
              if(this.actionToken){ //用原来的后面的操作指令 否则就用url parmas 的指令 默认 没有就空
                this.listQuery.actionInstruct =  this.actionToken
              }
              getCourseActionInstruct({ ...this.listQuery }).then((res) => {
                if (res.status === 0) {
                this.actionToken = res.result.actionToken //后面的操作指令
                 this.info.rateCard = res.result.accountCard
                // this.$route.query.actionToken?this.$route.query.actionToken:res.result.actionToken
                if (this.id||this.listQuery.actionInstruct) {
                  let data = res.result
                    if(data.courseInfo){
                      var { sport, // 运动id
                         course, // 课程id
                         courseDetails // 课程信息id
                          } = data.courseInfo

                         this.rollCallMethod = data.courseInfo.rollCallMethod?data.courseInfo.rollCallMethod:''
                         this.info.lesson.rateCard = data.courseInfo.rateCard?data.courseInfo.rateCard:''
                         this.info.course = { sport, // 运动id
                         course, // 课程id
                         courseDetails // 课程信息id
                        }
                        //debugger
                        console.log("手打",)
                        this.resetRouteTitle()
                       // debugger
                       this.course = true
                    }
                    if(data.list){
                      this.lesson = true
                      this.lessonList = data.list
                      this.listQuery.total = data.total ? data.total : this.listQuery.total
                      //this.listQuery.size = data.totalPage ? data.totalPage : this.listQuery.page
                    }

                }
                }
              })
            },
            fetchData() {

                // debugger
                var sortName = this.sortName
                 var paramCode = { code: sortName[0].typeCode + ',' + sortName[1].typeCode + ',' + sortName[2].typeCode + ',' + 'VENUE' }
                 getTypeCodeList(paramCode).then((res) => {
                   //debugger
                   sortName[0].list = res.result
                 })
              //this.trainScheduleList(this.listQuery.page, tabName)
            },
            addEdit(course,msg) {
              const that = this
              var courseInfo = this.info[course]
              console.log('resdddparams', courseInfo)
              // 执行指令
              courseInfo.rateCard = this.info.lesson.rateCard
              courseInfo.actionInstruct = this.actionToken
              addEdit(course, {size:this.listQuery.size,...courseInfo}).then((res) => {
                if (res.status === 0) {
                 that[course] = true
                 // for(var i in that.info[course]){
                 //   that.info[course][i]=''
                 // }
                 if (res.result.lessonList) {
                        const data = res.result
                        that.listQuery.total = data.total ? data.total : that.listQuery.total
                        //this.listQuery.page = data.totalPage ? data.totalPage : this.listQuery.page
                        that.lessonList=data.lessonList
                   console.log(courseInfo, 'success', that.lessonList)
                 }
                }
                 that['load' + course ]=false
                 if(!msg){
                   that.$message({
                     type: !res.status ? 'success' : 'warning',
                     message: res.msg
                   })
                 }

              })
            },
            confirmCourse(formName) {
              var _this = this
                this.$refs[formName].validate((valid) => {
                   console.log('valid', valid)
                  if (valid) {
                    _this['load' + formName ]=true
                    _this.addEdit(formName)
                  } else {
                    console.log('error submit!!')
                    return false
                  }
                })
              },
              resetForm(formName) {
                this.$refs[formName].resetFields()
              },
              close(id) {
                var that=this
                // this.lessonList.map((ins, i) => {
                // if (ins.id === id) {
                //   that.$set(that.lessonList,'edit',false)
                // }
                // })
               // that.lessonList=[]
              },
            del(id ) {
                 const that = this
                this.$confirm('This action will permanently delete this item. Do you want to continue?', 'Tips', {
                    confirmButtonText: 'Yes',
                    cancelButtonText: 'No',
                    type: 'warning'
                }).then((res) => {
                   delInfo('lesson', { lessonId: id, actionInstruct: that.actionToken }).then((res) => {
                        // this.$message({
                        //     message: res.msg.toLowerCase(),
                        //     type: res.status === 0 ? 'success' : 'warning'
                        // })
                        if(res.status === 0){
                          that.lessonList.map((item,ind)=>{
                             if(item.id===id) return that.lessonList.splice(ind,1)
                          })
                        }
                   })

                }).catch(() => {
                    // this.$message({
                    //     type: 'info',
                    //     message: '已取消删除'
                    // })
                })
            },
            onCopy(){
               //asyncGet
               if(this.multipleSelections.length===1){
                 let  Selectionslist = this.multipleSelections[0]
                 //let {id:lessonId,upperDate:date,endTime,location:venue} = this.multipleSelections[0],
                 //actionInstruct = this.actionToken
                 let b = {}
                 Object.assign(b,this.multipleSelections[0])

                 b.edit = true;
                 b.copy = true
                 b.upperDate = ''
                 b.status = 'ACTIVE'
                    this.lessonList.push(b)
                    this.$set(this,'lessonList',this.lessonList)
               }else{
                 this.$message({type:'warning',message:'You can only copy by radio'})
               }

             },
           confirmEdit(row) {
                  let list = this.lessonList
                   let { id, _startTime:startTime, _endTime:endTime, _location:location, _rateCard:rateCard, _upperDate:upperDate ,status} = row; const actionInstruct = this.actionToken
                   let row_params = {  startTime, endTime, rateCard,status }
                   if(row._startTime >= row._endTime){ //輸入開始結束時間的有誤的話
                     this.$message({type:'warning',message:'End time cannot be less than start time!'})
                    this.$set(row,'edit',true)
                   }

                        if(row.copy&&!upperDate){
                          row_params.date = upperDate
                          this.$set(row,'edit',true)
                          return this.$message({type:'warning',message:'Please input Date!'})
                        }
                        if(!row.copy){
                          row_params.upperDate = upperDate
                          row_params.id = id
                          row_params.location =  location
                        }else{

                          row_params.lessonId = id
                          row_params.date = upperDate
                          row_params.venue =  location

                        }
                      this[(row.copy?'copy':'update')+'Info'] ('lesson', {...row_params,actionInstruct}).then(response => {
                      if (response.status === 0) {
                        let resultLesson=response.result
                        for(var k in resultLesson ){

                          this.$set(row,k,resultLesson[k])
                        }
                  if(row.copy){
                    this.$set(row,'copy',false)
                  }
                      }
                      // this.$message({
                      //         message: response.msg,
                      //         type: response.status ? 'warning' : 'success'
                      //     })
                  })
              },
            indexMethod(index) {
            return index
            },
          selectSingle(sel, row) {
            this.indsignMd5 = row.signMd5
            //console.log('selectSingle', row, sel)
          },
          selectAll(selection){
            this.isAll=selection.length==this.lessonList.length
             console.log('ssssss',selection,this.isAll)
          },
          handleSelectionChange(val) {
             this.multipleSelection = []
             this.multipleSelections = val
             var that = this
             // that.arrayUnique2(val, 'signMd5')
            val.map((row,i) => {
                  that.multipleSelection.push(Number(row.id))
                  })
          },
          toEdit(lessonIds){
             const actionInstruct = encodeURIComponent(this.actionToken);
             lessonIds = JSON.stringify(lessonIds)
            this.$router.push({
                  name: '_train_Participact',
                  query: { lessonIds, actionInstruct, page: this.activeName,pageNum:this.listQuery.page,size:this.listQuery.size ,id:this.id}
            })
          },
          onBulkSubmit(row) {
            if (!this.multipleSelection) return this.$message.warning('Lesson list is No Data')
           // debugger
            // if (  this.bools ) return  this.$message.warning('必须要有相同的Coach/Helper/Athlete 才可以批量修改！')
            const that = this
            console.log("asds",that.multipleSelection,)
           let lessonIds = this.multipleSelection
                this.toEdit(lessonIds)
              },
              // 保存
              onSave() {
                const that = this
                   if (that['course'] && that['lesson']||this.$route.query.actionInstruct) {
                    updateInfo('course', { actionInstruct: that.actionToken }).then((res) => {
                     if (res.status === 0) {
                            that.$message.success(res.msg)
                            that.$router.push('/trainSchedule?tab=' + that.activeName)
                     }
                   })
                   }
                  if ((!that['course'] || !that['lesson'])&&!this.$route.query.actionInstruct) this.$message.warning('please fineshed Course information or Lesson information')
              },
            minWidth(i, text) {
                let w = 100
                if (text.length >= 10) {
                     w = 130
                } else if (text.length < 5 && text !== '') {
                     w = 50
                } else {
                     w = 100
                }
                // const w = text.length >= 10 ? 130 : 100
                console.log(text, text.length)
                return w
            },
            // pageSize变化事件
            handleSizeChange(val) {
              this.listQuery.size = val
              this.getCourseActionInstruct()
            },
            // pageNum变化事件
            handleCurrentChange(page) {
              this.listQuery.page = page
              this.getCourseActionInstruct()

            },
            sportMedicineFormatLink(row, column) {
                // eslint-disable-next-line no-return-assign
                return row.row.id = 1
            },
            forthSet(dateStr, pattern = '') {
                // 根据给定的时间字符串，得到特定的时间
                var dt = new Date(dateStr)
                //   yyyy-mm-dd
                var y = dt.getFullYear()
                var m = (dt.getMonth() + 1).toString().padStart(2, '0')
                var d = dt.getDate().toString().padStart(2, '0')
                if (pattern.toLowerCase() === 'yyyy-mm-dd') {
                    return `${y}-${m}-${d}`
                } else {
                    var hh = dt.getHours().toString().padStart(2, '0')
                    var mm = dt.getMinutes().toString().padStart(2, '0')
                    var ss = dt.getSeconds().toString().padStart(2, '0')
                    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
                }
            },

            change_time(e) {
              console.log('333', e)
              e.pickerVisible = true
            },

        headerChild() {
        },
        async onDetele(){
          //asyncGet
          if(this.multipleSelection.length){
            let lessonIds = this.multipleSelection,
            actionInstruct = this.actionToken

           let {status:lessonList} = await asyncGet('/course/manager/del/lesson_many','post','',{lessonIds,actionInstruct})
           if(lessonList===0){
             //copyList.edit = true
           var that = this
            // this.$set(copyList,'_'+i,copyList[i])
              lessonIds.map((lessn)=>{
             this.lessonList.map((listL,l,item)=>{
             // console.log('试试水',l,lessonIds[l],listL.id)

                if(lessn === listL.id){

                   that.lessonList.splice(l,1)

                }
              })

             })
                 that.$set(that,'lessonList',that.lessonList)
           }
          }

          // else{
          //   this.$message({type:'warning',message:'You can only copy by radio'})
          // }

        },


        onBack() {
                if (this.target === 'blank') {
                    console.log(this.$route)
                } else {
                    this.$router.back(-1)
                }
            },
            handleSelect(item) {
                this.followUpData.name = item.name
                this.followUpData.id = item.id
                // console.log(item)
            },
            grantAccesshandleSelect(item) {
                this.grantAccessData.name = item.name
                this.grantAccessData.id = item.id
            },
            athleteshandleSelect(item) {
                this.athleteData.name = item.name
                this.athleteData.id = item.id
                this.info.memberId = item.id
            },

            addFollowUp(name, id, type) {
                if (!name && !id) {
                    this.$message({
                        type: 'error',
                        message: 'Please select users'
                    })
                    return false
                }
                if (name && id) {
                  if (type === 'GrantAccess') {
                      const list = this.grantAccessData.list
                      for (var i in list) {
                        if (list[i].id === id) {
                          this.followUpData.name = ''
                          this.followUpData.id = ''
                          return false
                        }
                      }
                      list.push({ name: name, id: id })
                      this.grantAccessData.name = ''
                      this.grantAccessData.id = ''
                  } else {
                      const list = this.followUpData.list
                      for (var l in list) {
                       if (list[l].id === id) {
                         this.followUpData.name = ''
                         this.followUpData.id = ''
                         return false
                       }
                      }
                      list.push({ name: name, id: id })
                      this.followUpData.name = ''
                      this.followUpData.id = ''
                  }
                }
            },
            delFollowUp(key, type) {
                if (type === 'GrantAccess') {
                    const list = this.grantAccessData.list
                    list.splice(key, 1)
                } else {
                    const list = this.followUpData.list
                    list.splice(key, 1)
                }
            },

            in_array(search, array) {
                for (var i in array) {
                    // eslint-disable-next-line eqeqeq
                    if (array[i] === search) {
                        return true
                    }
                }
                return false
            }
        },
        beforeRouteLeave(to, from, next) {
            // this.$confirm('Do you really want to leave? you have unsaved changes?', '提示', {
            //     confirmButtonText: 'Yes',
            //     cancelButtonText: 'ON',
            //     type: 'warning'
            // }).then(() => {
            //     next()
            // }).catch(() => {
            //     next(false)
            // })
            next()
        }
    }
</script>
<style lang="scss">
  html{
    .el-time-spinner {
      >div:nth-child(2){
        .el-time-spinner__list{
          li{
            display: none;
            //visibility: hidden;
            &:nth-child(5n+1){
               display:block;
               //visibility:visible;
            }
          }
        }
      }
    }
  }
  html #courseAddEdit{
    // *, *:before, *:after{
    //   -webkit-box-sizing:border-box;
    //       box-sizing: border-box;;
    // }
    .el-table__body-wrapper{
   //  height:40vh;overflow-y: auto;
    tbody{
      >tr.el-table__row:last-child{
          .vue__time-picker{
            .dropdown{
              bottom:calc(2.2em + 2px) !important;;
              top:unset !important;
            }
          }
        }
    }
    }
    .starlOv{
      .cell {
        overflow: inherit !important;
      }
    }
.el-checkbox-button .el-checkbox-button__inner{
     padding:8px 10px;border-radius: 4px;
      }
   .el-form-item{
   flex: auto;
    text-align: center;

   }

   .vue__time-picker{
   width: 100%;
   input.display-time{
     width:100%;
   }
 .dropdown {
   z-index: 8888;
 }

   }
.timerBox{

   padding: 3px 10px;
   //line-height:40px;height: 40px;
   border: 1px solid rgba(151,151,151,0.3);
   border-radius: 4px;
   .el-form-item__content{line-height: inherit;}
       .vue__time-picker{
    width: 100%;
  // height:34px;

    input.display-time{
        width: 100%;
        background: #f3f5f7;
        border: 0;
        height:auto;
        font-size: 14px;
        padding: 6px 8px;
        //line-height: 40px;
    }
    .dropdown{
       width:100%;
       *{ width:100%;}
      ul{

         li{
           line-height: 35px;color: inherit;
         }
      }
    }
      }

     }
  }
</style>
<style lang="scss" scoped>

 .call_method_box .el-col{
  line-height: 40px;
 }

 .app-container .add-page{
   min-height:80vh;
   position: relative;
  // .el-button{margin: 10px 0;}
   .solid-row{
     padding:0 15px;
   }
    .iconBtn i{
      &.editOk{
        color: red;
      }
      font-size: 1.2rem;
    }
   .ul-input{
         margin:10px 0;
   }
   .el-select{
   padding: 0;
   display: block;
   .el-input__inner{
      display: block;
   }
 }

//    .el-form-item{
//    position: absolute;bottom: 0;width:100%;
//  }
   }
</style>
